# coding = utf-8

import pdb
from bmob import *

b = Bmob("f5b3dbd027720a6f49c87b6a1a1c7a84", "616ee9149ae817bcd2f535b9a21050d4")

def append_to_bmob(province, city, display_name):
    # 插入一行数据，原子计数、Pointer
    print(
	b.insert(
		't_city', # 表名
		BmobUpdater.increment(
            "count", 2,
			{ # 城市信息
				"province": province, #省份
				"city": city, # 城市
                "city_display" : display_name, #城市别名
			}
		)
	).jsonData # 输出json格式的内容
)

def append_to_bmob(province, city_list):
    print(
        b.insert(
		't_new_city', # 表名
		BmobUpdater.increment(
            "count", 2,
			{ # 城市信息
				"province": province, #省份
				"cities": city_list, # 城市
			}
		)
	).jsonData # 输出json格式的内容
)

def getCityDisplayName(city_name):
    index = -1
    display_name = city_name
    lst_filter_xinjiang = ["回族","哈萨克","蒙古"]
    lst_filter_yunnan = ["白族","哈尼族","彝族","壮族","藏族","傈僳族","傣族","市","地区","自治州"]
    lst_filter = lst_filter_xinjiang + lst_filter_yunnan
    for filter in lst_filter:
        index = city_name.find(filter)
        if index >= 0:
            display_name = city_name[0:index]
            #pdb.set_trace()
            break
    return display_name

def parse_file():
    file_handle = open('china_city.txt', encoding='UTF-8', errors='ignore')
    contents = file_handle.readlines()
    dict_city = {}
    for content in contents:
        if content.strip() == '':
            continue
        #pdb.set_trace()
        lst_city = []
        country = content.split(' ',4)[0]
        code = content.split(' ',4)[1]
        province = content.split(' ',4)[2]
        city = content.split(' ',4)[3].strip()
        display_name = getCityDisplayName(city)
        #pdb.set_trace()
        if province in dict_city:
            lst_city = dict_city[province]
        lst_city.append(display_name)
        dict_city[province] = lst_city
        #append_to_bmob(province,city,display_name)
    pdb.set_trace()
    for (k,v) in dict_city.items():
        append_to_bmob(k, v)
    file_handle.close()
    print('Just Done.')

if __name__ == '__main__':
    parse_file()